package com.example.myapplication.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.SwapHoriz
import androidx.compose.animation.*
import androidx.compose.material3.*
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.example.myapplication.ui.components.StorageItemRow
import com.example.myapplication.ui.components.StorageSpaceCard
import com.example.myapplication.ui.components.StorageSpaceRow
import com.example.myapplication.ui.components.BreadcrumbNavigation
import com.example.myapplication.ui.components.AddItemDialog
import com.example.myapplication.ui.components.AddStorageSpaceDialog
import com.example.myapplication.ui.components.LoadingState
import com.example.myapplication.ui.components.ErrorState
import com.example.myapplication.ui.components.EmptyState
import com.example.myapplication.ui.components.ErrorSnackbar
import com.example.myapplication.ui.components.ActionBottomSheet
import com.example.myapplication.ui.components.ActionItem
import com.example.myapplication.ui.components.ItemActionHandler
import com.example.myapplication.ui.components.MoveItemDialog
import com.example.myapplication.data.model.StorageSpace
import com.example.myapplication.data.model.StorageItem
import com.example.myapplication.data.model.BreadcrumbItem
import com.example.myapplication.viewmodel.StorageDetailViewModel

/**
 * 储物空间详情界面 - 显示子空间和物品的条目列表
 */
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun StorageDetailScreen(
    spaceId: String,
    onNavigateBack: () -> Unit,
    onNavigateToStorageDetail: (String) -> Unit,
    onNavigateToItemDetail: (String) -> Unit,
    onNavigateToSearch: () -> Unit,
    viewModel: StorageDetailViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    val snackbarHostState = remember { SnackbarHostState() }
    var showAddSpaceDialog by remember { mutableStateOf(false) }
    var showAddItemDialog by remember { mutableStateOf(false) }
    var showAddChoiceDialog by remember { mutableStateOf(false) }
    var showSpaceActionSheet by remember { mutableStateOf(false) }
    var showItemActionSheet by remember { mutableStateOf(false) }
    var selectedSpace by remember { mutableStateOf<StorageSpace?>(null) }
    var selectedItem by remember { mutableStateOf<StorageItem?>(null) }
    var spaceToEdit by remember { mutableStateOf<StorageSpace?>(null) }
    var showEditSpaceDialog by remember { mutableStateOf(false) }
    
    
    
    // 加载数据
    LaunchedEffect(spaceId) {
        viewModel.loadStorageDetail(spaceId)
    }
    
    // 处理错误消息
    LaunchedEffect(uiState.errorMessage) {
        uiState.errorMessage?.let { message ->
            snackbarHostState.showSnackbar(
                message = message,
                actionLabel = "关闭"
            )
            viewModel.clearErrorMessage()
        }
    }
    
    // 处理成功消息
    LaunchedEffect(uiState.successMessage) {
        uiState.successMessage?.let { message ->
            snackbarHostState.showSnackbar(
                message = message,
                duration = SnackbarDuration.Short
            )
            viewModel.clearSuccessMessage()
        }
    }
    
    // 空间删除确认对话框
    if (uiState.spaceToDelete != null && uiState.deleteConfirmationInfo != null) {
        AlertDialog(
            onDismissRequest = { viewModel.cancelSpaceDeletion() },
            title = { 
                Text(
                    text = "确认删除",
                    style = MaterialTheme.typography.headlineSmall
                ) 
            },
            text = { 
                Text(
                    text = uiState.deleteConfirmationInfo!!,
                    style = MaterialTheme.typography.bodyMedium
                ) 
            },
            confirmButton = {
                Button(
                    onClick = { viewModel.confirmSpaceDeletion() },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text("确认删除")
                }
            },
            dismissButton = {
                TextButton(onClick = { viewModel.cancelSpaceDeletion() }) {
                    Text("取消")
                }
            }
        )
    }

    // 删除确认对话框
    uiState.itemToDelete?.let { item ->
        AlertDialog(
            onDismissRequest = { viewModel.onDeleteItemCancelled() },
            title = { Text("确认删除物品") },
            text = { Text("您确定要删除物品 '${item.name}' 吗？此操作无法撤销。") },
            confirmButton = {
                TextButton(onClick = { viewModel.onDeleteItemConfirmed() }) {
                    Text("确认删除")
                }
            },
            dismissButton = {
                TextButton(onClick = { viewModel.onDeleteItemCancelled() }) {
                    Text("取消")
                }
            }
        )
    }


    Scaffold(
        topBar = {
            TopAppBar(
                title = { 
                    if (uiState.breadcrumbs.isNotEmpty()) {
                        BreadcrumbNavigation(
                            breadcrumbs = uiState.breadcrumbs,
                            onBreadcrumbClick = { breadcrumbId ->
                                // 如果是主页，则导航回主页
                                if (breadcrumbId == "root") {
                                    onNavigateBack()
                                } else {
                                    viewModel.navigateToSpace(breadcrumbId)
                                }
                            }
                        )
                    } else {
                        Text(uiState.currentSpace?.name ?: "储物空间")
                    }
                },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                actions = {
                    IconButton(onClick = { 
                        // 触发编辑当前储物空间
                        uiState.currentSpace?.let { space ->
                            spaceToEdit = space
                            showEditSpaceDialog = true
                        }
                    }) {
                        Icon(
                            imageVector = Icons.Default.Edit,
                            contentDescription = "编辑储物空间"
                        )
                    }
                }
            )
        },
        floatingActionButton = {
            FloatingActionButton(onClick = { showAddChoiceDialog = true }) {
                Icon(Icons.Default.Add, contentDescription = "添加")
            }
        },
        snackbarHost = {
            ErrorSnackbar(snackbarHostState = snackbarHostState)
        }
    ) { paddingValues ->
        when {
            uiState.isLoading -> {
                LoadingState(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues),
                    message = "加载储物空间详情..."
                )
            }
            
            uiState.currentSpace == null -> {
                ErrorState(
                    message = "储物空间不存在",
                    onRetry = { viewModel.loadStorageDetail(spaceId) },
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues)
                )
            }
            
            else -> {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues)
                ) {
                    // 移除原来的面包屑导航，现在在TopAppBar中显示
                    
                    // 子空间部分
                    if (uiState.childSpaces.isNotEmpty()) {
                        Text(
                            text = "子空间 (${uiState.childSpaces.size})",
                            style = MaterialTheme.typography.titleMedium,
                            color = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
                        )
                        
                        LazyVerticalGrid(
                            columns = GridCells.Fixed(1),
                            contentPadding = PaddingValues(horizontal = 16.dp),
                            verticalArrangement = Arrangement.spacedBy(8.dp),
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            items(
                                items = uiState.childSpaces,
                                key = { it.id }
                            ) { space ->
                                StorageSpaceRow(
                                    space = space,
                                    onClick = { 
                                        println("DEBUG: StorageDetailScreen onClick for space: ${space.name}, id: ${space.id}")
                                        onNavigateToStorageDetail(space.id) 
                                    },
                                    onLongClick = { 
                                        println("DEBUG: StorageDetailScreen onLongClick for space: ${space.name}")
                                        selectedSpace = space
                                        showSpaceActionSheet = true 
                                    },
                                    modifier = Modifier.animateItemPlacement()
                                )
                            }
                        }
                        
                        Spacer(modifier = Modifier.height(16.dp))
                    }
                    
                    // 物品部分
                    if (uiState.items.isNotEmpty()) {
                        Text(
                            text = "物品 (${uiState.items.size})",
                            style = MaterialTheme.typography.titleMedium,
                            color = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
                        )
                        
                        LazyColumn(
                            contentPadding = PaddingValues(horizontal = 16.dp),
                            verticalArrangement = Arrangement.spacedBy(8.dp),
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            items(
                                items = uiState.items,
                                key = { it.id }
                            ) { item ->
                                StorageItemRow(
                                    item = item,
                                    onClick = { onNavigateToItemDetail(item.id) },
                                    onLongClick = { 
                                        selectedItem = item
                                        showItemActionSheet = true
                                    },
                                    modifier = Modifier.animateItemPlacement()
                                )
                            }
                        }
                    }
                    
                    // 空状态
                    if (uiState.childSpaces.isEmpty() && uiState.items.isEmpty()) {
                        EmptyState(
                            title = "空间为空",
                            description = "还没有子空间或物品\n点击右下角的 + 按钮开始添加",
                            modifier = Modifier.fillMaxSize()
                        )
                    }
                }
            }
        }
    }
    
    // 选择添加类型的对话框
    if (showAddChoiceDialog) {
        AlertDialog(
            onDismissRequest = { showAddChoiceDialog = false },
            title = { Text("选择添加类型") },
            text = {
                Column(modifier = Modifier.fillMaxWidth()) {
                    TextButton(
                        onClick = {
                            showAddChoiceDialog = false
                            showAddSpaceDialog = true
                        },
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Text("添加子空间")
                    }
                    TextButton(
                        onClick = {
                            showAddChoiceDialog = false
                            showAddItemDialog = true
                        },
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Text("添加物品")
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { showAddChoiceDialog = false }) {
                    Text("取消")
                }
            }
        )
    }

    // 添加储物空间对话框
    if (showAddSpaceDialog) {
        AddStorageSpaceDialog(
            onDismiss = { showAddSpaceDialog = false },
            onConfirm = { name, description, iconType ->
                viewModel.addChildSpace(name, description, iconType)
                showAddSpaceDialog = false
            }
        )
    }
    
    // 添加物品对话框
    if (showAddItemDialog) {
        AddItemDialog(
            onDismiss = { showAddItemDialog = false },
            onConfirm = { name, description, quantity, imageUrl ->
                viewModel.addItem(name, description, quantity, imageUrl)
                showAddItemDialog = false
            }
        )
    }
    
    // 储物空间长按操作菜单
    if (showSpaceActionSheet && selectedSpace != null) {
        ActionBottomSheet(
            onDismiss = { 
                showSpaceActionSheet = false
                selectedSpace = null
            },
            title = selectedSpace!!.name,
            actions = listOf(
                ActionItem(
                    title = "修改",
                    icon = Icons.Default.Edit,
                    onClick = {
                        spaceToEdit = selectedSpace
                        showEditSpaceDialog = true
                        showSpaceActionSheet = false
                        selectedSpace = null
                    }
                ),
                ActionItem(
                    title = "删除",
                    icon = Icons.Default.Delete,
                    onClick = {
                        selectedSpace?.let { space ->
                            viewModel.deleteSpace(space)
                        }
                        showSpaceActionSheet = false
                        selectedSpace = null
                    },
                    isDestructive = true
                )
            )
        )
    }

    if (showEditSpaceDialog && spaceToEdit != null) {
        AddStorageSpaceDialog(
            onDismiss = { showEditSpaceDialog = false },
            onConfirm = { name, description, iconType ->
                spaceToEdit?.let { 
                    viewModel.updateSpace(it.id, name, description, iconType) 
                }
                showEditSpaceDialog = false
            },
            isEditMode = true,
            initialName = spaceToEdit!!.name,
            initialDescription = spaceToEdit!!.description ?: "",
            initialIconType = spaceToEdit!!.iconType
        )
    }
    
    // 物品长按操作菜单
    ItemActionHandler(
        selectedItem = selectedItem,
        showItemActionSheet = showItemActionSheet,
        onDismissActionSheet = {
            showItemActionSheet = false
            selectedItem = null
        },
        viewModel = viewModel
    )




}